package com.deanlib.cabinet.service;

import android.content.Intent;
import android.text.TextUtils;

import com.deanlib.cabinet.app.Constants;
import com.deanlib.cabinet.base.BaseService;
import com.deanlib.cabinet.data.AppDatabase;
import com.deanlib.cabinet.data.db.ResourceDao;
import com.deanlib.cabinet.data.model.Resource;
import com.deanlib.cabinet.data.network.schedulers.SchedulerProvider;
import com.deanlib.cabinet.utils.ConfigManager;
import com.elvishew.xlog.XLog;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.functions.Function;


/**
 * 资源备份服务
 * 通过给定的本地或者远端备份服务器地址，将原始数据进行备份
 * @Created by Dean
 * @Date 2023/6/18
 */
public class ResourceBackupService extends BaseService {

    @Override
    public void onCreate() {
        super.onCreate();
//        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!TextUtils.isEmpty(ConfigManager.getInstance().getOriginalResourceBackupServiceUrl())){
            //测试是否是备份服务器
            //todo 通过一个接口验证
            if (false) {
                //是备份服务器
                List<Resource> resources = AppDatabase.getDaoSession().getResourceDao().queryBuilder()
                        .where(ResourceDao.Properties.BackedUp.notEq(true)).list();
                addDisposable(Observable.fromIterable(resources).map(resource -> {
                    //备份上传
                    //todo 上传接口

                    if (false) {
                        //备份成功
                        Resource dbRes = AppDatabase.getDaoSession().getResourceDao().load(resource.md5);
                        dbRes.backedUp = true;
                        AppDatabase.getDaoSession().getResourceDao().update(dbRes);
                    }

                    return resource.md5;
                }).compose(SchedulerProvider.getInstance().applySchedulers()).subscribe());
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getNotifyId() {
        return Constants.SERVICE_NOTIFY_ID_RESOURCE_BACKUP;
    }


}
